#include <jni.h>
#include <string>
#include "onvifmsg.h"
#include "Log.h"
#include "device.h"


map<string, Device> map_device;
extern "C" JNIEXPORT jstring JNICALL
Java_com_pqtel_libonvif_LibOnvif_init(
        JNIEnv *env,
        jobject /* this */,
        jstring username,
        jstring pwd,
        jstring ip) {
    LOGD("init------->first1","");
    char *cusername = (char *) env->GetStringUTFChars(username, JNI_FALSE);
    char *cpwd = (char *) env->GetStringUTFChars(pwd, JNI_FALSE);
    char *cip = (char *) env->GetStringUTFChars(ip, JNI_FALSE);
    Device *device = new Device(cusername, cpwd,cip);
    LOGD("init------->first2","");
    map_device.insert(pair<string, Device>(cip,*device));
//    LOGD("init------->first3","");
    std::string hello = "Hello from C++";
//    LOGD("init------->end4","");
    return env->NewStringUTF(hello.c_str());
}


extern "C" JNIEXPORT
jint JNICALL
Java_com_pqtel_libonvif_LibOnvif_doPtz(
        JNIEnv *env,
        jobject /* this */,
        jstring ip, jint ptz_command, jfloat ptz_speed) {
    char *cip = (char *) env->GetStringUTFChars(ip, JNI_FALSE);
    auto map_it=map_device.find(cip);
    int reuslt = map_it->second.DoPtz(5,ptz_command,ptz_speed);
    return reuslt;
}


extern "C" JNIEXPORT
jstring JNICALL
Java_com_pqtel_libonvif_LibOnvif_getOnvifMediaUri(
        JNIEnv *env,
        jobject /* this */,
        jstring ip) {
    char *cip = (char *) env->GetStringUTFChars(ip, JNI_FALSE);
    auto map_it=map_device.find(cip);
    map_it->second.GetOnvifMediaUri();
    LOGD("getOnvifMediaUri device,ip:%s username:%s",cip,map_it->second.username.data());
    string url_reuslt;
    auto ite = map_it->second.map_passmsg.begin();
    for (ite; ite != map_it->second.map_passmsg.end(); ite++) {
        LOGD("map->item:%s,value:%s,token:%s", (*ite).first.data(), (*ite).second.uri,
             (*ite).second.token);
        url_reuslt.append((*ite).second.uri);
        if ((*ite).second.uri!=NULL&&(*ite).second.uri[0]!='\0'){
            url_reuslt.append("$");
        }
    }
    return  env->NewStringUTF(url_reuslt.data());
}

extern "C" JNIEXPORT
void JNICALL
Java_com_pqtel_libonvif_LibOnvif_setTokenByUri(
        JNIEnv *env,
        jobject /* this */,
        jstring ip,
        jstring uri){
    LOGD("setTokenByUri:start", "");
    char *cip = (char *) env->GetStringUTFChars(ip, JNI_FALSE);
    auto map_it=map_device.find(cip);
    char *c_uri = (char *) env->GetStringUTFChars(uri, JNI_FALSE);
    map_it->second.SetTokenByUri(c_uri);
}


extern "C" JNIEXPORT
jint JNICALL
Java_com_pqtel_libonvif_LibOnvif_doPtzStop(
        JNIEnv *env,
        jobject /* this */,
        jstring ip) {
    char *cip = (char *) env->GetStringUTFChars(ip, JNI_FALSE);
    auto map_it=map_device.find(cip);
    int result = map_it->second.PtzStop();
    LOGD("ptz stop:%d", 0);
    return result;
}
